<template>
  <view class="chat-container">
    <!-- 重连提示 -->
    <view v-if="reconnecting" class="reconnect-banner">
      <text>🔄</text>
      <text>实时服务连接中，部分功能暂不可用...</text>
    </view>
    
    <!-- 聊天头部组件 -->
    <ChatHeader 
      :userName="currentChatUser.name"
      :isOnline="currentChatUser.isOnline"
      :connectionStatus="connectionStatus"
      @back="goBack"
      @call="makeCall"
      @more="showMoreOptions"
    />

    <!-- 消息列表 -->
    <scroll-view 
      ref="scrollView"
      class="message-list" 
      scroll-y="true" 
      :scroll-top="scrollTop"
      :scroll-with-animation="true"
      :scroll-into-view="scrollIntoView"
      @scrolltoupper="loadMoreMessages"
    >
      <!-- 加载更多提示 -->
      <view v-if="loadingMore" class="loading-more">
        <text class="loading-text">加载更多消息...</text>
      </view>
      
      <!-- 消息气泡组件 -->
      <MessageBubble 
        v-for="(message, index) in visibleMessages" 
        :key="message.id || index"
        :message="message"
        :isMine="isMyMessage(message)"
        @preview-image="previewImage"
      />
    </scroll-view>

    <!-- 输入区域组件 -->
    <MessageInput 
      :value="inputMessage"
      @input="handleInput"
      @send="sendMessage"
      @show-emoji="showEmojiPicker"
      @choose-image="chooseImage"
      @choose-file="chooseFile"
      @show-voice="showVoiceRecord"
      @focus="scrollToBottom"
    />

    <!-- 表情选择器 -->
    <SheetModal 
      :visible="showEmojiModal" 
      title="选择表情" 
      :show-close="true"
      @close="closeEmojiModal"
    >
      <view class="emoji-grid">
        <view 
          v-for="emoji in emojis" 
          :key="emoji"
          class="emoji-item"
          @click="insertEmoji(emoji)"
        >
          {{ emoji }}
        </view>
      </view>
    </SheetModal>

    <!-- 更多选项弹窗 -->
    <SheetModal 
      :visible="showMoreOptionsModal" 
      title="更多选项" 
      :show-close="true"
      @close="closeMoreOptions"
    >
      <view class="options-list">
        <view class="option-item" @click="clearMessages">
          <text class="option-icon">🗑️</text>
          <text class="option-text">清空消息</text>
        </view>
        <view class="option-item" @click="exportMessages">
          <text class="option-icon">📤</text>
          <text class="option-text">导出聊天记录</text>
        </view>
        <view class="option-item" @click="showChatSettings">
          <text class="option-icon">⚙️</text>
          <text class="option-text">聊天设置</text>
        </view>
      </view>
    </SheetModal>
  </view>
</template>

<script>
import chatService from '../../utils/websocket-chat-service.js'
import apiService from '../../utils/api-service.js'
import appStateManager from '../../utils/app-state-manager.js'
import connectionManager from '../../utils/connection-manager.js'
import chatMessageManager from '../../utils/chat-message-manager.js'
import ChatHeader from './components/ChatHeader.vue'
import MessageBubble from './components/MessageBubble.vue'
import MessageInput from './components/MessageInput.vue'
import SheetModal from '../../components/SheetModal.vue'

export default {
  components: {
    ChatHeader,
    MessageBubble,
    MessageInput,
    SheetModal
  },
  
  data() {
    return {
      messages: [],
      inputMessage: '',
      currentChatUser: {
        id: '',
        name: '聊天用户',
        avatar: '',
        isOnline: true
      },
      roomId: '',
      scrollTop: 0,
      scrollIntoView: '',
      loadingMore: false,
      isSending: false,
      maxVisibleMessages: 50,
      serverOnline: false,
      chatConnected: false,
      reconnecting: false,
      showEmojiModal: false,
      showMoreOptionsModal: false,
      emojis: ['😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣', '😊', '😇', '🙂', '🙃', '😉', '😌', '😍', '🥰', '😘', '😗', '😙', '😚', '😋', '😛', '😝', '😜', '🤪', '🤨', '🧐', '🤓', '😎', '🤩', '🥳', '😏', '😒', '😞', '😔', '😟', '😕', '🙁', '☹️', '😣', '😖', '😫', '😩', '🥺', '😢', '😭', '😤', '😠', '😡', '🤬', '🤯', '😳', '🥵', '🥶', '😱', '😨', '😰', '😥', '😓']
    }
  },
  
  computed: {
    visibleMessages() {
      if (this.messages.length <= this.maxVisibleMessages) {
        return this.messages
      }
      return this.messages.slice(-this.maxVisibleMessages)
    },
    
    connectionStatus() {
      if (!this.serverOnline) return 'disconnected'
      if (!this.chatConnected) return 'disconnected'
      if (this.reconnecting) return 'reconnecting'
      return 'connected'
    }
  },
  
  async onLoad(options) {
    console.log('聊天页面加载，参数:', options)
    
    try {
      if (!options || !options.userId) {
        throw new Error('缺少必要的用户ID参数')
      }
      
      this.currentChatUser = {
        id: options.userId,
        name: options.userName || '聊天用户',
        avatar: '',
        isOnline: false
      }
      
      this.roomId = this.generateRoomId()
      this.initStateSubscriptions()
      this.subscribeToMessages()
      
      await this.initChatService()
      
      if (chatService.isConnected) {
        setTimeout(async () => {
          try {
            await chatService.joinRoom(this.roomId)
            await this.loadHistoryMessages()
          } catch (e) {
            console.error('加入房间失败:', e)
            uni.showToast({ title: '加入聊天室失败', icon: 'none' })
          }
        }, 1000)
      }
    } catch (error) {
      console.error('聊天页面加载失败:', error)
      uni.showModal({
        title: '加载失败',
        content: error.message || '聊天页面加载失败',
        showCancel: false,
        success: () => {
          uni.navigateBack()
        }
      })
    }
  },
  
  async onShow() {
    setTimeout(() => {
      appStateManager.refreshServerStatus()
      if (chatService.isConnected) {
        chatService.requestOnlineUsers()
      }
    }, 500)
  },
  
  async onUnload() {
    try { 
      await chatService.leaveRoom(this.roomId) 
    } catch (e) {
      console.error('离开房间失败:', e)
    }
    this.cleanup()
  },
  
  methods: {
    // ========== 状态管理 ==========
    initStateSubscriptions() {
      appStateManager.subscribe('server', (serverState) => {
        this.serverOnline = serverState.isOnline
      })
      
      appStateManager.subscribe('chat', (chatState) => {
        this.chatConnected = chatState.isConnected
        this.reconnecting = chatState.reconnectAttempts > 0
      })
      
      connectionManager.setWebSocketService(chatService)
      connectionManager.start()
    },
    
    subscribeToMessages() {
      chatMessageManager.subscribe(this.roomId, (messages) => {
        this.messages = messages
        this.$nextTick(() => {
          this.scrollToBottom()
        })
      })
    },
    
    generateRoomId() {
      const currentUser = this.getCurrentUser()
      if (!currentUser || !this.currentChatUser.id) {
        return `room_${Date.now()}`
      }
      
      return chatMessageManager.generateRoomId([
        currentUser.id.toString(),
        this.currentChatUser.id.toString()
      ], 'private')
    },
    
    // ========== 消息操作 ==========
    async sendMessage() {
      if (!this.inputMessage.trim() || this.isSending) return
      
      const messageText = this.inputMessage.trim()
      this.inputMessage = ''
      this.isSending = true
      
      try {
        const currentUser = this.getCurrentUser()
        const tempMessage = {
          id: `temp_${Date.now()}`,
          content: messageText,
          type: 'text',
          sender: {
            id: currentUser.id,
            name: currentUser.name,
            avatar: currentUser.avatar
          },
          timestamp: new Date().toISOString(),
          status: 'sending'
        }
        
        this.messages.push(tempMessage)
        this.$nextTick(() => this.scrollToBottom())
        
        await chatService.sendMessage({
          roomId: this.roomId,
          content: messageText,
          type: 'text',
          receiverId: this.currentChatUser.id
        })
        
        tempMessage.status = 'sent'
      } catch (error) {
        console.error('发送消息失败:', error)
        uni.showToast({ title: '发送失败', icon: 'error' })
      } finally {
        this.isSending = false
      }
    },
    
    handleInput(value) {
      this.inputMessage = value
    },
    
    async loadHistoryMessages() {
      try {
        const cachedMessages = chatMessageManager.getMessages(this.roomId)
        if (cachedMessages.length > 0) {
          this.messages = cachedMessages
          this.$nextTick(() => this.scrollToBottom())
        }
      } catch (error) {
        console.error('加载历史消息失败:', error)
      }
    },
    
    async loadMoreMessages() {
      if (this.loadingMore) return
      this.loadingMore = true
      
      setTimeout(() => {
        this.loadingMore = false
      }, 1000)
    },
    
    isMyMessage(message) {
      const currentUser = this.getCurrentUser()
      return currentUser && message.sender?.id === currentUser.id
    },
    
    // ========== UI操作 ==========
    scrollToBottom() {
      this.$nextTick(() => {
        this.scrollTop = 99999
      })
    },
    
    previewImage(imageUrl) {
      uni.previewImage({
        urls: [imageUrl],
        current: imageUrl
      })
    },
    
    showEmojiPicker() {
      this.showEmojiModal = true
    },
    
    closeEmojiModal() {
      this.showEmojiModal = false
    },
    
    insertEmoji(emoji) {
      this.inputMessage += emoji
      this.closeEmojiModal()
    },
    
    chooseImage() {
      uni.chooseImage({
        count: 1,
        success: (res) => {
          console.log('选择图片:', res.tempFilePaths[0])
        }
      })
    },
    
    chooseFile() {
      uni.showToast({ title: '文件发送功能开发中', icon: 'none' })
    },
    
    showVoiceRecord() {
      uni.showToast({ title: '语音功能开发中', icon: 'none' })
    },
    
    // ========== 更多操作 ==========
    goBack() {
      uni.navigateBack()
    },
    
    makeCall() {
      uni.showToast({ title: '通话功能开发中', icon: 'none' })
    },
    
    showMoreOptions() {
      this.showMoreOptionsModal = true
    },
    
    closeMoreOptions() {
      this.showMoreOptionsModal = false
    },
    
    clearMessages() {
      uni.showModal({
        title: '清空消息',
        content: '确定要清空所有消息吗？',
        success: (res) => {
          if (res.confirm) {
            chatMessageManager.clearMessages(this.roomId)
            this.messages = []
            this.closeMoreOptions()
            uni.showToast({ title: '已清空消息', icon: 'success' })
          }
        }
      })
    },
    
    exportMessages() {
      uni.showToast({ title: '导出功能开发中', icon: 'none' })
      this.closeMoreOptions()
    },
    
    showChatSettings() {
      uni.showToast({ title: '设置功能开发中', icon: 'none' })
      this.closeMoreOptions()
    },
    
    // ========== 工具方法 ==========
    getCurrentUser() {
      try {
        const currentUser = uni.getStorageSync('currentUser')
        return currentUser ? JSON.parse(currentUser) : null
      } catch (error) {
        console.error('获取当前用户失败:', error)
        return null
      }
    },
    
    async initChatService() {
      try {
        if (!chatService.isConnected) {
          await chatService.init()
        }
        
        chatService.onMessage((data) => {
          if (data.roomId === this.roomId) {
            chatMessageManager.addMessage(this.roomId, data)
          }
        })
        
        chatService.onFriendOnlineStatus((data) => {
          if (data.userId === this.currentChatUser.id) {
            this.currentChatUser.isOnline = data.isOnline
          }
        })
      } catch (error) {
        console.error('初始化聊天服务失败:', error)
      }
    },
    
    cleanup() {
      connectionManager.stop()
      chatMessageManager.unsubscribe(this.roomId)
    }
  }
}
</script>

<style scoped>
.chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.reconnect-banner {
  background: #fffbe6;
  color: #8c6d1f;
  padding: 12rpx 20rpx;
  font-size: 22rpx;
  border-bottom: 1rpx solid #f0e6cc;
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.message-list {
  flex: 1;
  overflow-y: auto;
}

.loading-more {
  text-align: center;
  padding: 20rpx;
}

.loading-text {
  font-size: 22rpx;
  color: #999;
}

/* 表情网格 */
.emoji-grid {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 16rpx;
  padding: 20rpx;
  max-height: 600rpx;
  overflow-y: auto;
}

.emoji-item {
  font-size: 48rpx;
  text-align: center;
  padding: 16rpx;
  cursor: pointer;
  transition: transform 0.2s;
}

.emoji-item:active {
  transform: scale(1.2);
}

/* 选项列表 */
.options-list {
  padding: 16rpx 0;
}

.option-item {
  display: flex;
  align-items: center;
  gap: 16rpx;
  padding: 24rpx 32rpx;
  transition: background 0.3s ease;
}

.option-item:active {
  background: #f8f9fa;
}

.option-icon {
  font-size: 32rpx;
}

.option-text {
  font-size: 26rpx;
  color: #333;
}
</style>

